<script setup>
import { ref, watch } from 'vue'
import { SearchCategoryService, SearchAllService } from '@/apis/search.js'
import { debounce } from 'lodash'
import { useSearchStore } from '@/stores/index.js'

const SearchStore = useSearchStore()

// 搜索框双向绑定的搜索关键字
const keyWords = ref('')

// 存储搜索到的数据
const searchList = ref([])

const props = defineProps({
	switch: {
		type: Boolean,
		default: false
	},
	searchAll: {
		type: Boolean,
		default: true
	},
	keyword: {
		type: String,
		default: ''
	}
})

watch(
	() => props.keyword,
	(newValue, oldValue) => {
		if (newValue !== oldValue) {
			keyWords.value = newValue
		}
	}
)

const emits = defineEmits(['search'])

// 点击搜索框跳转到搜索页面
const onClickSearch = () => {
	uni.navigateTo({
		url: '/ExplorePackage/Search/Search'
	})
}

// 搜索数据功能
const SearchFunction = async () => {
	if (props.searchAll === true) {
		const res = await SearchAllService(keyWords.value)
		searchList.value = res.data
		emits('search', searchList.value)
	} else {
		const res = await SearchCategoryService(keyWords.value)
		searchList.value = res.data
		emits('search', searchList.value)
	}
}

// 创建防抖函数实例,对搜索框搜索函数进行防抖处理
const debounceLoadData = debounce(SearchFunction, 1000)

// 确认搜索关键词进行搜索
const confirmSearch = () => {
	if (props.searchAll === true && keyWords.value.trim() !== '') {
		if (!SearchStore.searchHistoryData.includes(keyWords.value)) {
			SearchStore.setSearchHistoryData(keyWords.value)
		}

		debounceLoadData()
	}
}
</script>

<template>
	<up-search
		v-model="keyWords"
		bgColor="#fff"
		borderColor="#f53b22"
		searchIconColor="#f53b22"
		:show-action="props.switch"
		actionText="搜索"
		:actionStyle="{ backgroundColor: '#f53b22', borderRadius: '15rpx', color: '#fff', height: '60rpx', lineHeight: '60rpx', textAlign: 'center' }"
		shape="round"
		:clearabled="true"
		margin="30rpx 10rpx"
		:disabled="!props.switch"
		:animation="props.switch"
		@click="onClickSearch"
		@custom="confirmSearch"
		@search="confirmSearch"
		@change="debounceLoadData"
	></up-search>
</template>

<style lang="scss" scoped></style>
